/* 
 * File: Camera2D
 * Created: 16-JUN-2011
 * Author: Colin Gall-McDaid
 * 
 * Description: 2D camera class used to setup the viewport and frustrum.
 */
package com.gallsoft.games.framework.gl;

import javax.microedition.khronos.opengles.GL10;

import com.gallsoft.games.framework.impl.GLGraphics;
import com.gallsoft.games.framework.math.Vector2;


public class Camera2D {

    public final Vector2 position;
    public final float frustrumWidth;
    public final float frustrumHeight;
    private final GLGraphics glGraphics;
    public float zoom;
    private  Vector2 maxPosition;
    
    public Camera2D(GLGraphics glGraphics, float frustrumWidth, float frustrumHeight) {
        this.glGraphics = glGraphics;
        this.frustrumWidth = frustrumWidth;
        this.frustrumHeight = frustrumHeight;
        this.position = new Vector2(frustrumWidth / 2, frustrumHeight / 2);
        this.zoom = 1.0f;
        //this.zoom = 0.5f;
    }
    
    /**
     * Set up the viewport
     */
    public void setViewportAndMatrices() {
        GL10 gl = glGraphics.getGL();
        gl.glViewport(0, 0, glGraphics.getWidth(), glGraphics.getHeight());
        gl.glMatrixMode(GL10.GL_PROJECTION);
        gl.glLoadIdentity();
        gl.glOrthof(position.x - frustrumWidth * zoom / 2,
                    position.x + frustrumWidth * zoom / 2,
                    position.y - frustrumHeight * zoom / 2,
                    position.y + frustrumHeight * zoom / 2,
                    1, -1);
        gl.glMatrixMode(GL10.GL_MODELVIEW);
        gl.glLoadIdentity();
    }
    
    /**
     * Convert touch screen coordinates to game world coordinates.
     * 
     * @param touch
     *          touch screen vector
     */
    public void touchToWorld(Vector2 touch) {
        touch.x = (touch.x / (float)glGraphics.getWidth()) * frustrumWidth * zoom;
        touch.y = (1 - touch.y / (float)glGraphics.getHeight()) * frustrumHeight * zoom;
        touch.add(position).sub(frustrumWidth * zoom / 2, frustrumHeight * zoom / 2);
    }
    
    public void setMaxPosition(Vector2 maxPosition) {
        this.maxPosition = maxPosition;
    }
    
    public float getMaxXPosition() {
        return maxPosition.x;
    }
    
    public float getMaxYPosition() {
        return maxPosition.y;
    }
}
